package marker.fun;

import freemarker.core.Environment;
import freemarker.template.*;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * as变量转换类型
 * Created by Administrator on 2016/12/28.
 */
public class AsType implements TemplateDirectiveModel
{
    public void execute(Environment env,
                        Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body)
            throws TemplateException, IOException
    {
        if (!params.isEmpty()) {
            throw new TemplateModelException(
                    "This directive doesn't allow parameters.");
        }
        if (loopVars.length != 0) {
            throw new TemplateModelException(
                    "This directive doesn't allow loop variables.");
        }

        if (body != null) {
            body.render(new UpperCaseFilterWriter(env.getOut()));
        } else {
            throw new RuntimeException("missing body");
        }
    }

    /**
     * A {@link Writer} that transforms the character stream to upper case
     * and forwards it to another {@link Writer}.
     */
    private static class UpperCaseFilterWriter extends Writer
    {

        private final Writer out;

        UpperCaseFilterWriter(Writer out)
        {
            this.out = out;
        }

        public void write(char[] cbuf, int off, int len)
                throws IOException
        {
            String str = new String(cbuf).trim();
            if(str.equals("int")){
                str= "int";
            }else if(str.equals("long")){
                str= "Number";
            }else if(str.equals("short")){
                str= "int";
            }else if(str.equals("byte")){
                str= "int";
            }else if(str.equals("double")){
                str= "Number";
            }else if(str.equals("float")){
                str= "Number";
            }else if(str.equals("boolean")){
                str= "Boolean";
            }

            out.write(str);
        }

        public void flush() throws IOException
        {
            out.flush();
        }

        public void close() throws IOException
        {
            out.close();
        }
    }
}
